<template>
  <ElDialog
    v-model="dialogVisible"
    title="库存历史记录"
    width="1400px"
    :close-on-click-modal="false"
    destroy-on-close
    append-to-body
  >
    <div v-if="detailData" class="history-content">
      <!-- 基本信息 -->
      <ElCard class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <ElIcon><Box /></ElIcon>
            <span>商品信息</span>
          </div>
        </template>

        <ElDescriptions :column="4" size="small" border>
          <ElDescriptionsItem label="商品名称">
            {{ detailData.item?.itemName || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="商品编号">
            {{ detailData.item?.itemCode || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="规格名称">
            {{ detailData.itemSku?.skuName || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="规格编号">
            {{ detailData.itemSku?.skuCode || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="仓库">
            {{ detailData.warehouseName || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="库区">
            {{ detailData.areaName || "-" }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="当前库存">
            <ElStatistic
              :value="Number(detailData.remainQuantity || 0)"
              :precision="0"
            />
          </ElDescriptionsItem>
          <ElDescriptionsItem label="批号">
            {{ detailData.batchNo || "-" }}
          </ElDescriptionsItem>
        </ElDescriptions>
      </ElCard>

      <!-- 搜索条件 -->
      <ElCard class="search-card" shadow="never">
        <ElForm :model="queryForm" :inline="true" label-width="80px">
          <ElFormItem label="操作类型">
            <ElRadioGroup v-model="queryForm.orderType" @change="handleSearch">
              <ElRadioButton :label="-1">全部</ElRadioButton>
              <ElRadioButton
                v-for="item in inventoryHistoryTypes"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>

          <ElFormItem label="操作单号">
            <ElInput
              v-model="queryForm.orderNo"
              placeholder="请输入操作单号"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>

          <ElFormItem label="操作时间">
            <ElDatePicker
              v-model="queryForm.createTimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
            />
          </ElFormItem>

          <ElFormItem>
            <ElButton type="primary" icon="Search" @click="handleSearch"
              >搜索</ElButton
            >
            <ElButton icon="Refresh" @click="handleReset">重置</ElButton>
          </ElFormItem>
        </ElForm>
      </ElCard>

      <!-- 历史记录表格 -->
      <ElCard class="table-card" shadow="never">
        <template #header>
          <div class="card-header">
            <ElIcon><Clock /></ElIcon>
            <span>操作记录</span>
          </div>
        </template>

        <ElTable
          v-loading="loading"
          :data="historyList"
          border
          stripe
          cell-class-name="vertical-top-cell"
          empty-text="暂无操作记录"
        >
          <ElTableColumn label="操作单号" prop="orderNo" width="160" />

          <ElTableColumn label="操作类型" width="100" align="center">
            <template #default="{ row }">
              <ElTag :type="getOperationTagType(row.orderType)">
                {{ getOperationText(row.orderType) }}
              </ElTag>
            </template>
          </ElTableColumn>

          <ElTableColumn label="商品信息" width="200">
            <template #default="{ row }">
              <div class="item-info">
                <div class="item-name">{{ row.item?.itemName || "-" }}</div>
                <div v-if="row.item?.itemCode" class="item-code">
                  商品编号：{{ row.item.itemCode }}
                </div>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="规格信息" width="200">
            <template #default="{ row }">
              <div class="sku-info">
                <div class="sku-name">{{ row.itemSku?.skuName || "-" }}</div>
                <div v-if="row.itemSku?.skuCode" class="sku-code">
                  规格编号：{{ row.itemSku.skuCode }}
                </div>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="仓库/库区" width="180">
            <template #default="{ row }">
              <div class="warehouse-info">
                <div>仓库：{{ row.warehouseName || "-" }}</div>
                <div>库区：{{ row.areaName || "-" }}</div>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="数量/价格" width="140" align="right">
            <template #default="{ row }">
              <div class="quantity-info">
                <div class="quantity-row">
                  <span class="label">数量：</span>
                  <ElStatistic
                    :value="Number(row.quantity || 0)"
                    :precision="0"
                    class="inline-statistic"
                  />
                </div>
                <div v-if="row.amount !== undefined" class="price-row">
                  <span class="label">价格：</span>
                  <ElStatistic
                    :value="Number(row.amount || 0)"
                    :precision="2"
                    class="inline-statistic"
                  />
                </div>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="批号" prop="batchNo" width="120" />

          <ElTableColumn label="生产日期/过期日期" width="180">
            <template #default="{ row }">
              <div class="date-info">
                <div v-if="row.productionDate">
                  生产日期：{{ formatDate(row.productionDate) }}
                </div>
                <div v-if="row.expirationDate">
                  过期日期：{{ formatDate(row.expirationDate) }}
                </div>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="操作时间" prop="createTime" width="160" />
        </ElTable>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <ElPagination
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </ElCard>

      <!-- 统计信息 -->
      <ElCard class="stats-card" shadow="never">
        <template #header>
          <div class="card-header">
            <ElIcon><TrendCharts /></ElIcon>
            <span>统计信息</span>
          </div>
        </template>

        <ElRow :gutter="24">
          <ElCol :span="6">
            <div class="stat-item">
              <div class="stat-label">总记录数</div>
              <div class="stat-value">{{ total }}</div>
            </div>
          </ElCol>
          <ElCol :span="6">
            <div class="stat-item">
              <div class="stat-label">入库次数</div>
              <div class="stat-value in">{{ getOperationCount(1) }}</div>
            </div>
          </ElCol>
          <ElCol :span="6">
            <div class="stat-item">
              <div class="stat-label">出库次数</div>
              <div class="stat-value out">{{ getOperationCount(2) }}</div>
            </div>
          </ElCol>
          <ElCol :span="6">
            <div class="stat-item">
              <div class="stat-label">其他操作</div>
              <div class="stat-value other">{{ getOtherOperationCount() }}</div>
            </div>
          </ElCol>
        </ElRow>
      </ElCard>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false" v-ripple> 关闭 </ElButton>
        <ElButton type="primary" @click="handleExport" v-ripple>
          <ElIcon><Download /></ElIcon>
          导出历史
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Box, Clock, TrendCharts, Download } from "@element-plus/icons-vue";
import { formatDate } from "@/utils/date";

// 定义接口
interface ItemInfo {
  itemName?: string;
  itemCode?: string;
}

interface SkuInfo {
  skuName?: string;
  skuCode?: string;
}

interface InventoryDetailInfo {
  id: number;
  remainQuantity: number;
  batchNo?: string;
  warehouseName?: string;
  areaName?: string;
  item?: ItemInfo;
  itemSku?: SkuInfo;
}

interface HistoryItem {
  id: number;
  orderNo?: string;
  orderType: number;
  quantity: number;
  amount?: number;
  batchNo?: string;
  productionDate?: string;
  expirationDate?: string;
  createTime?: string;
  warehouseName?: string;
  areaName?: string;
  item?: ItemInfo;
  itemSku?: SkuInfo;
}

interface HistoryQueryParams {
  pageNum: number;
  pageSize: number;
  orderType: number;
  orderNo?: string;
  createTimeRange?: string[];
  itemName?: string;
  itemCode?: string;
  skuName?: string;
  skuCode?: string;
  warehouseId?: number;
  areaId?: number;
}

// 定义props和emits
interface Props {
  visible?: boolean;
  detailData?: InventoryDetailInfo | null;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  detailData: null,
});

const emit = defineEmits<Emits>();

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value: boolean) => {
    emit("update:visible", value);
  },
});

// 数据状态
const loading = ref(false);
const historyList = ref<HistoryItem[]>([]);
const total = ref(0);

// 默认时间
const defaultTime = reactive([
  new Date(0, 0, 0, 0, 0, 0),
  new Date(0, 0, 0, 23, 59, 59),
]);

// 查询表单
const queryForm = reactive<HistoryQueryParams>({
  pageNum: 1,
  pageSize: 10,
  orderType: -1,
  orderNo: undefined,
  createTimeRange: undefined,
  itemName: undefined,
  itemCode: undefined,
  skuName: undefined,
  skuCode: undefined,
  warehouseId: undefined,
  areaId: undefined,
});

// 库存历史操作类型（模拟字典数据）
const inventoryHistoryTypes = ref([
  { value: 1, label: "入库" },
  { value: 2, label: "出库" },
  { value: 3, label: "调整" },
  { value: 4, label: "盘点" },
  { value: 5, label: "移库" },
]);

/**
 * 监听对话框显示状态
 */
watch(
  () => props.visible,
  (visible) => {
    if (visible && props.detailData) {
      // 重置查询条件
      resetQueryForm();
      // 加载历史数据
      loadHistoryData();
    }
  },
);

/**
 * 重置查询表单
 */
function resetQueryForm(): void {
  Object.assign(queryForm, {
    pageNum: 1,
    pageSize: 10,
    orderType: -1,
    orderNo: undefined,
    createTimeRange: undefined,
  });
}

/**
 * 加载历史数据
 */
async function loadHistoryData(): Promise<void> {
  if (!props.detailData) return;

  loading.value = true;
  try {
    // TODO: 调用库存历史API
    // const query = { ...queryForm }
    // if (query.orderType === -1) {
    //   query.orderType = null
    // }
    // if (query.createTimeRange) {
    //   query.startTime = query.createTimeRange[0]
    //   query.endTime = query.createTimeRange[1]
    // }
    // const response = await listInventoryHistory(query)
    // historyList.value = response.rows
    // total.value = response.total

    // 模拟数据
    await new Promise((resolve) => setTimeout(resolve, 500));

    const mockData: HistoryItem[] = [
      {
        id: 1,
        orderNo: "RK20241201001",
        orderType: 1,
        quantity: 100,
        amount: 5000.0,
        batchNo: "BATCH001",
        productionDate: "2024-11-01",
        expirationDate: "2025-11-01",
        createTime: "2024-12-01 10:30:00",
        warehouseName: "主仓库",
        areaName: "A区",
        item: {
          itemName: "测试商品",
          itemCode: "ITEM001",
        },
        itemSku: {
          skuName: "规格A",
          skuCode: "SKU001",
        },
      },
      {
        id: 2,
        orderNo: "CK20241202001",
        orderType: 2,
        quantity: 20,
        amount: 1000.0,
        batchNo: "BATCH001",
        productionDate: "2024-11-01",
        expirationDate: "2025-11-01",
        createTime: "2024-12-02 14:20:00",
        warehouseName: "主仓库",
        areaName: "A区",
        item: {
          itemName: "测试商品",
          itemCode: "ITEM001",
        },
        itemSku: {
          skuName: "规格A",
          skuCode: "SKU001",
        },
      },
    ];

    // 根据查询条件过滤数据
    let filteredData = mockData;
    if (queryForm.orderType !== -1) {
      filteredData = filteredData.filter(
        (item) => item.orderType === queryForm.orderType,
      );
    }
    if (queryForm.orderNo) {
      filteredData = filteredData.filter((item) =>
        item.orderNo?.includes(queryForm.orderNo!),
      );
    }

    historyList.value = filteredData;
    total.value = filteredData.length;
  } catch (error) {
    console.error("加载历史数据失败:", error);
    ElMessage.error("加载历史数据失败");
  } finally {
    loading.value = false;
  }
}

/**
 * 搜索处理
 */
function handleSearch(): void {
  queryForm.pageNum = 1;
  loadHistoryData();
}

/**
 * 重置处理
 */
function handleReset(): void {
  resetQueryForm();
  loadHistoryData();
}

/**
 * 分页大小变化
 */
function handleSizeChange(size: number): void {
  queryForm.pageSize = size;
  loadHistoryData();
}

/**
 * 当前页变化
 */
function handleCurrentChange(current: number): void {
  queryForm.pageNum = current;
  loadHistoryData();
}

/**
 * 导出历史
 */
async function handleExport(): Promise<void> {
  try {
    // TODO: 调用导出API
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
}

/**
 * 获取操作类型标签类型
 */
function getOperationTagType(orderType: number): string {
  const typeMap: Record<number, string> = {
    1: "success", // 入库
    2: "warning", // 出库
    3: "info", // 调整
    4: "primary", // 盘点
    5: "danger", // 移库
  };
  return typeMap[orderType] || "default";
}

/**
 * 获取操作类型文本
 */
function getOperationText(orderType: number): string {
  const type = inventoryHistoryTypes.value.find(
    (item) => item.value === orderType,
  );
  return type?.label || "未知";
}

/**
 * 获取操作类型统计
 */
function getOperationCount(orderType: number): number {
  return historyList.value.filter((item) => item.orderType === orderType)
    .length;
}

/**
 * 获取其他操作统计
 */
function getOtherOperationCount(): number {
  return historyList.value.filter((item) => ![1, 2].includes(item.orderType))
    .length;
}
</script>

<style lang="scss" scoped>
.history-content {
  .info-card,
  .search-card,
  .table-card,
  .stats-card {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }

  .search-card {
    :deep(.el-form-item) {
      margin-bottom: 16px;
    }
  }

  .table-card {
    :deep(.el-table) {
      .vertical-top-cell {
        vertical-align: top;
      }

      .item-info,
      .sku-info {
        .item-name,
        .sku-name {
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .item-code,
        .sku-code {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }

      .warehouse-info {
        font-size: 14px;
        line-height: 1.4;
      }

      .quantity-info {
        .quantity-row,
        .price-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 4px;

          .label {
            font-size: 12px;
            color: var(--el-text-color-regular);
          }

          .inline-statistic {
            :deep(.el-statistic__content) {
              font-size: 14px;
            }
          }
        }
      }

      .date-info {
        font-size: 12px;
        line-height: 1.4;
        color: var(--el-text-color-regular);
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .stats-card {
    .stat-item {
      text-align: center;

      .stat-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);

        &.in {
          color: var(--el-color-success);
        }

        &.out {
          color: var(--el-color-warning);
        }

        &.other {
          color: var(--el-color-info);
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
